package vn.edu.tdt.it.entity;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import vn.edu.tdt.it.common.VietnameseProcessing;
import vn.edu.tdt.it.domain.StaticConnection;

public class Category {
	int id;
	String name;
	List<Category> subCategories = null;
	List<Page> subPages = null;
	public String nonNomalized;
	
	public Category(int id, String name) {
		this.id = id;
		setName(name);
		nonNomalized = name.replaceAll("_", " ");
	}
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = VietnameseProcessing.removeSpecialChar(name);
	}
	
	public List<Category> getSubCategories() throws Exception {
		if(subCategories == null) {
			subCategories = new ArrayList<Category>();
			String sql = "SELECT outLinks FROM category_outlinks WHERE id = ?";
			PreparedStatement ps = StaticConnection.getPreparedStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				sql = "SELECT name FROM category WHERE id = ?";
				ps = StaticConnection.getPreparedStatement(sql);
				ps.setInt(1, rs.getInt(1));
				ResultSet rs2 = ps.executeQuery();
				while (rs2.next()) {
					Category p = new Category(rs.getInt(1), rs2.getString(1));
					subCategories.add(p);
				}
			}
		}
		return subCategories;
	}
	
	public List<Page> getPages() throws Exception {
		if(subPages == null) {
			subPages = new ArrayList<Page>();
			String sql = "SELECT pages FROM category_pages WHERE id = ?";
			PreparedStatement ps = StaticConnection.getPreparedStatement(sql);
			ps.setInt(1, id);
			ResultSet rs = ps.executeQuery();
			while (rs.next()) {
				sql = "SELECT name FROM page WHERE id = ?";
				ps = StaticConnection.getPreparedStatement(sql);
				ps.setInt(1, rs.getInt(1));
				ResultSet rs2 = ps.executeQuery();
				while (rs2.next()) {
					Page p = new Page(rs.getInt(1), rs2.getString(1));
					subPages.add(p);
				}
			}
		}
		return subPages;
	}
	public void setSubCategories(Object object) {
		subCategories=null;
		subPages=null;
	}
}
